package com.example.demo.common;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.AuthenticationToken;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT; 
import com.example.demo.shiro.ShiroSimpleJwtToken;
 
import lombok.extern.log4j.Log4j2; 

@Log4j2
public class JwtTokenUtils {

	/**
	 * 序化列 token 对象
	 * @param token
	 * @return
	 */
	public static ShiroSimpleJwtToken serializeToken(String token) {
		
		log.info("序列化token: "+token);		
		ShiroSimpleJwtToken tokenInfo=new ShiroSimpleJwtToken();		 
		DecodedJWT jwt=JWT.decode(token);		
		tokenInfo.setExpireTime(jwt.getExpiresAt());		  
		tokenInfo.setUsername(jwt.getAudience().get(0));
		
//		List<String> userinfo= jwt.getClaim("userinfo")
//				.asList(String.class);
//		System.out.println(userinfo);			
		 
//		tokenInfo.setHost(jwt.getClaim("host").asString());
		tokenInfo.setUserId(jwt.getClaim("userId").asString());	
		
		System.out.println(tokenInfo);
		
		return tokenInfo;	
		
	}
	
	/**
	 * 反序列化 token 对象
	 * @param token
	 * @return
	 */
	public static String deserializeString(ShiroSimpleJwtToken token) {	

	    String tokenString= JWT.create().withExpiresAt(token.getExpireTime())
	    		.withAudience(token.getUsername())
	    		
//	    		.withArrayClaim("userinfo", new String[] {//	                  
//	                 token.getUserId()
//	    		})	    		
	    		 
//	    		.withClaim("host", token.getHost())
	    		.withClaim("userId", token.getUserId())	    		
	    		
                .sign(Algorithm.HMAC256(new String(token.getPassword())));      
	    
		return tokenString;	
		
	}
	
}
